package com.demo.java8Stream;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 使用JAVA8实现对list<Map<String,Object>>的integer类型的weight字段值进行倒序排列，并将weight的null值放在最后
 */
public class ListSortTest {

    // 要对 List<Map<String, Integer>> 中的 Integer 类型字段 weight 进行倒序排列，
    // 并将 weight 的 null 值排在最后，可以使用 Java 8 的 Stream API 来实现。以下是一个示例代码：

    public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map10 = new HashMap<>();
        map10.put("weight", null);
        map10.put("id", "10");
        list.add(map10);

        Map<String, Object> map11 = new HashMap<>();
        map11.put("weight", 11);
        map11.put("id", "11");
        list.add(map11);
        // 添加示例数据
        Map<String, Object> map1 = new HashMap<>();
        map1.put("weight", 5);
        map1.put("id", "5");
        list.add(map1);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("weight", 2);
        map2.put("id", "2");
        list.add(map2);

        Map<String, Object> map3 = new HashMap<>();
        map3.put("weight", null);
        map3.put("id", "3");
        list.add(map3);

        Map<String, Object> map4 = new HashMap<>();
        map4.put("weight", 4);
        map4.put("id", "4");
        list.add(map4);


        //【java8方法排序  倒叙实现】
        List<Map<String, Object>> sortedList = list.stream()
                .sorted(Comparator.comparing(map -> (Integer) map.getOrDefault("weight", Integer.MAX_VALUE), Comparator.nullsLast(Comparator.reverseOrder())))
                .collect(Collectors.toList());
        System.err.printf("sortedList=" + sortedList);
//执行结果 sortedList=[{weight=11, id=11}, {weight=5, id=5}, {weight=4, id=4}, {weight=2, id=2}, {weight=null, id=10}, {weight=null, id=3}]
        //【实现方法1】
           /* Collections.sort(list, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Integer resignDate1 = (Integer) o1.get("weight");
                    Integer resignDate2 = (Integer) o2.get("weight");
                    if (resignDate1 == null && resignDate2 == null) {
                        return 0;
                    } else if (resignDate1 == null) {
                        return 1;
                    } else if (resignDate2 == null) {
                        return -1;
                    }
                    return resignDate2.compareTo(resignDate1);   //此时为升序， return value2.compareTo(value1);为降序
                }
            });*/
        // System.err.printf("list="+ list);
        // 输出排序结果
        //sortedList.forEach(System.out::println);
        // System.err.printf("sortedList="+ JSON.toJSONString(sortedList));

    }
}
